<?php

namespace app\api\Logic;

use app\api\model\BrowseLogModel;
use app\api\model\LikesModel;
use app\api\model\ShareModel;
use app\common\model\Comment;
use think\Cache;
use think\Db;

class CommonLogic
{
    /**
     * 点击点赞按钮操作
     *
     * @param [type] $user_id 用户id
     * @param [type] $shop_id 校区id
     * @param [type] $relation_id 关联id
     * @param [type] $style 关联类型
     * @param [type] $db_name 需要更新的数据表名称，传入后，点赞操作后对应的表数据字段是自增自减
     * @param [type] $db_field 需要更新的数据表点赞数字段
     * @return void  当前点赞状态：1=未点赞，2=已点赞，false=错误
     */
    public function giveLikes($user_id,$shop_id,$relation_id,$style,$db_name='',$db_field='')
    {
        $likesModel = new LikesModel();
        $res = $this->isLike($user_id,$shop_id,$relation_id,$style);

        Db::startTrans();
        try {
            if($res){//存在 取消点赞
                $likesModel->where('id',$res['id'])->delete(); 
                if($db_name && $db_field){
                    Db::name($db_name)->where('id',$relation_id)->setDec($db_field);
                }
            }else{//不存在 点赞
                $likesModel->save([
                    'user_id' => $user_id,
                    'shop_id' => $shop_id,
                    'style' => $style,
                    'relation_id' => $relation_id,
                    'type' => 2,
                ]);
                if($db_name && $db_field){
                    Db::name($db_name)->where('id',$relation_id)->setInc($db_field);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
        return $res?1:2;
    }

    /**
     * 是否已点赞
     *
     * @param [type] $user_id 用户id
     * @param [type] $shop_id 校区id
     * @param [type] $relation_id 关联id
     * @param [type] $style 关联类型
     * @return void  点赞数据，未点赞为空
     */
    public function isLike($user_id,$shop_id,$relation_id,$style)
    {
        $likesModel = new LikesModel();
        $where = [
            'user_id' => $user_id,
            'shop_id' => $shop_id,
            'style' => $style,
            'relation_id' => $relation_id,

            
        ];
        $res = $likesModel->where($where)->field('id')->find();
        return $res;
    }


    /**
     * 获取帐号昵称头像
     *
     * @param [type] $type 类型0=平台帐号，1=校区帐号，2=用户帐号
     * @param [type] $id 帐号id
     * @return array
     */
    public function getUserInfo($type,$id)
    {
        $return['nickname'] = '';
        $return['avatar'] = '';
        $where['id'] = $id;
        $data = [];
        switch($type){  //用户数据缓存一天
            case 0: //总部
                $cahce_info = $this->userCache('user_info_admin_'.$id);
                if($cahce_info){
                    $data = $cahce_info;
                }else{
                    $data = model('AdminModel')->where($where)->field('nickname,avatar')->find();
                    Cache::set('user_info_admin_'.$id,$data,3600 * 24);
                }
                break;
            case 1: //校区服务商
                $cahce_info = $this->userCache('user_info_manystore_'.$id);
                if($cahce_info){
                    $data = $cahce_info;
                }else{
                    $data = model('ManystoreModel')->where($where)->field('username as nickname,avatar')->find();
                    Cache::set('user_info_manystore_'.$id,$data,3600 * 24);
                }
                break;
            case 2: //用户
                $cahce_info = $this->userCache('user_info_user_'.$id);
                if($cahce_info){
                    $data = $cahce_info;
                }else{
                    $data = model('user')->where($where)->field('truename as nickname,avatar')->find();
                    Cache::set('user_info_user_'.$id,$data,3600 * 24);
                }
            case 3: //老师
                $cahce_info = $this->userCache('user_info_manystore_'.$id);
                if($cahce_info){
                    $data = $cahce_info;
                }else{
                    $data = model('ManystoreModel')->where($where)->field('username as nickname,avatar')->find();
                    Cache::set('user_info_manystore_'.$id,$data,3600 * 24);
                }
        }
        if($data){
            $return['nickname'] = $data['nickname'];
            $return['avatar'] = $data['avatar'];
        }

        return $return;

    }
    /**
     * 获取缓存
     *
     * @param [type] $cache_name
     * @return void
     */
    public function userCache($cache_name)
    {
        if(Cache::has($cache_name)){
            return Cache::get($cache_name);
        }
        return false;
    }



    /**
     * 分享成功处理
     *
     * @param [type] $user_id 用户id
     * @param [type] $shop_id 校区id
     * @param [type] $relation_id 关联id
     * @param [type] $style 关联类型
     * @param [type] $db_name 需要更新的数据表名称
     * @param [type] $db_field 需要更新的数据表字段
     * @return bool   
     */
    public function handleShare($user_id,$shop_id,$relation_id,$style,$db_name='',$db_field='')
    {
        $shareModel = new ShareModel();
        $res = $this->isShare($user_id,$shop_id,$relation_id,$style);

        Db::startTrans();
        try {
            if(!$res){//不存在 添加分享信息并数量+1
                $shareModel->save([
                    'user_id' => $user_id,
                    'shop_id' => $shop_id,
                    'style' => $style,
                    'relation_id' => $relation_id,
                    'type' => 2,
                ]);
                if($db_name && $db_field){
                    Db::name($db_name)->where('id',$relation_id)->setInc($db_field);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
        return true;
    }

    /**
     * 是否已分享
     *
     * @param [type] $user_id 用户id
     * @param [type] $shop_id 校区id
     * @param [type] $relation_id 关联id
     * @param [type] $style 关联类型
     * @return void  分享数据，未分享为空
     */
    public function isShare($user_id,$shop_id,$relation_id,$style)
    {
        $shareMode = new ShareModel();
        $where = [
            'user_id' => $user_id,
            'shop_id' => $shop_id,
            'style' => $style,
            'relation_id' => $relation_id,

            
        ];
        $res = $shareMode->where($where)->field('id')->find();
        return $res;
    }

    /**
     * 发布评论
     *
     * @param [type] $shop_id 校区id
     * @param [type] $style  关联模型
     * @param [type] $reply_type 关联id
     * @param [type] $relation_id 贴子id
     * @param [type] $reply_id  用户id
     * @param [type] $content  评论内容
     * @param integer $to_id  回复的评论id
     * @return void
     */
    public function insertComment($shop_id,$style,$reply_type,$relation_id,$reply_id,$content,$to_id=0)
    {
        // 组装评论
        $param = [
            'style' => $style,
            'relation_id' => $relation_id,
            'reply_type' => $reply_type,
            'reply_id' => $reply_id,
            'content' => $content,
            'to_id' => $to_id,
        ];
        $comment_model = new Comment();
        $res = $comment_model->insertComment($shop_id,$param);
        return $res;
    }


    /**
     * 获取评论列表
     *
     * @param [type] $style
     * @param [type] $relation_id
     * @param [type] $page
     * @param [type] $limit
     * @return void
     */
    public function getCommentList($style,$relation_id,$page,$limit)
    {
        $where = [
            'a.style' => $style,
            'a.relation_id' => $relation_id,
            'a.top_id' => 0,
            'a.deletetime' => null,
        ];

        $res = model('CommentModel')
        ->alias('a')
        ->where($where)
        ->with(['son']) 
        ->limit(($page-1)*$limit,$limit)
        ->order('a.createtime desc')
        ->field('a.id,a.top_id,a.shop_id,a.relation_id,a.reply_type,a.reply_id,a.content,a.createtime')
        ->select();

        if($res){
            foreach ($res as &$v) {
                $user_info = $this->getUserInfo($v['reply_type'],$v['reply_id']);
                $v['nickname'] = $user_info['nickname'];
                $v['avatar'] = $user_info['avatar'];
                if($v['son']){
                    foreach ($v['son'] as $son_v) {
                        // 评论人
                        $son_user_info = $this->getUserInfo($son_v['reply_type'],$son_v['reply_id']);
                        $son_v['nickname'] = $son_user_info['nickname'];
                        $son_v['avatar'] = $son_user_info['avatar'];
                        // 回复的人
                        $reply_user_info = $this->getUserInfo($son_v['to_reply_type'],$son_v['to_reply_id']);
                        $son_v['reply_nickname'] = $reply_user_info['nickname'];
                        $son_v['reply_avatar'] = $reply_user_info['avatar'];
                    }
                }
            }
        }
        return $res;
    }


    /**
     * 已浏览，写入浏览历史
     *
     * @param [type] $user_id 用户id
     * @param [type] $shop_id 校区id
     * @param [type] $relation_id 关联id
     * @param [type] $style 关联类型
     * @param [type] $db_name 需要更新的数据表名称，传入后，点赞操作后对应的表数据字段是自增自减
     * @param [type] $db_field 需要更新的数据表点赞数字段
     * @return void  当前点赞状态：1=未点赞，2=已点赞，false=错误
     */
    public function alreadyView($user_id,$shop_id,$relation_id,$style,$db_name='',$db_field='')
    {
        $browseModel = new BrowseLogModel();
        $where = [
            'user_id' => $user_id,
            'shop_id' => $shop_id,
            'style' => $style,
            'relation_id' => $relation_id,
        ];
        $res = $browseModel->where($where)->field('id')->find();
        Db::startTrans();
        try {
            if($res){//存在 查看次数+1
                $browseModel->where('id',$res['id'])->setInc('num');
            }else{//不存在
                $browseModel->save([
                    'user_id' => $user_id,
                    'shop_id' => $shop_id,
                    'style' => $style,
                    'relation_id' => $relation_id,
                    'type' => 2,
                    'num' => 1
                ]);
            }
            if($db_name && $db_field){
                Db::name($db_name)->where('id',$relation_id)->setInc($db_field);
            }
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
        return true;
    }

}
